<template>
  <div class="user-management">
    <h2>用户管理</h2>
    
    <!-- 搜索和添加按钮区域 -->
    <div class="search-add-area">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="handleAddUser">添加用户</el-button>
    </div>
    
    <!-- 用户列表表格 -->
    <el-table :data="userList" style="width: 100%">
      <el-table-column prop="id" label="用户ID" width="80" />
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.updateTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEditUser(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDeleteUser(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[5, 10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 添加/编辑用户对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form :model="userForm" :rules="rules" ref="userFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item v-if="!userForm.id" label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item v-else label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" placeholder="请输入修改密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import userApi from '../apis/user';

// 响应式数据
const userList = ref([]);
const searchForm = reactive({
  username: ''
});
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});
const dialogVisible = ref(false);
const dialogTitle = ref('');
const userForm = reactive({
  id: null,
  username: '',
  password: ''
});
const userFormRef = ref();

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
};

// 生命周期
onMounted(() => {
  getUserList();
});

// 获取用户列表
const getUserList = async () => {
  try {
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      username: searchForm.username
    };
    const response = await userApi.getUserList(params);
    userList.value = response.data.records;
    pagination.total = response.data.total;
  } catch (error) {
    ElMessage.error('获取用户列表失败');
    console.error('获取用户列表失败:', error);
  }
};

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  getUserList();
};

// 重置
const handleReset = () => {
  searchForm.username = '';
  pagination.currentPage = 1;
  getUserList();
};

// 添加用户
const handleAddUser = () => {
  dialogTitle.value = '添加用户';
  // 重置表单
  userForm.id = null;
  userForm.username = '';
  userForm.password = '';
  if (userFormRef.value) {
    userFormRef.value.resetFields();
  }
  dialogVisible.value = true;
};

// 编辑用户
const handleEditUser = async (user) => {
  dialogTitle.value = '编辑用户';
  try {
    const response = await userApi.getUserById(user.id);
    // 复制用户数据，但不复制密码
    userForm.id = response.data.id;
    userForm.username = response.data.username;
    userForm.password = '';
    dialogVisible.value = true;
  } catch (error) {
    ElMessage.error('获取用户信息失败');
  }
};

// 删除用户
const handleDeleteUser = (id) => {
  ElMessageBox.confirm('确定要删除这个用户吗？', '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await userApi.deleteUser(id);
      ElMessage.success('删除成功');
      getUserList();
    } catch (error) {
      ElMessage.error('删除失败');
    }
  }).catch(() => {
    // 取消删除
  });
};

// 提交表单
const handleSubmit = async () => {
  if (!userFormRef.value) return;
  
  try {
    await userFormRef.value.validate();
    
    // 如果是编辑且密码为空，不修改密码
    const submitData = { ...userForm };
    if (submitData.id && !submitData.password) {
      delete submitData.password;
    }
    
    if (submitData.id) {
      // 编辑用户
      await userApi.updateUser(submitData);
      ElMessage.success('更新成功');
    } else {
      // 添加用户
      await userApi.addUser(submitData);
      ElMessage.success('添加成功');
    }
    
    dialogVisible.value = false;
    getUserList();
  } catch (error) {
    // 表单验证失败不处理
    if (error.message) {
      ElMessage.error(error.message.includes('用户名已') ? error.message : '操作失败');
    }
  }
};

// 分页处理
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  getUserList();
};

const handleCurrentChange = (current) => {
  pagination.currentPage = current;
  getUserList();
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
</script>

<style scoped>
.user-management {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
}

.user-management h2 {
  margin-bottom: 20px;
  color: #333;
}

.search-add-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>